package net.suncaper.hotel.web.controller;

import net.suncaper.hotel.common.framework.RequestMapping;
import net.suncaper.hotel.common.utils.JSONUtil;
import net.suncaper.hotel.common.utils.PageInfo;
import net.suncaper.hotel.common.utils.Result;
import net.suncaper.hotel.model.dto.CheckInDTO;
import net.suncaper.hotel.model.vo.CheckInVO;
import net.suncaper.hotel.model.vo.UserVO;
import net.suncaper.hotel.service.ICheckInService;
import net.suncaper.hotel.service.impl.CheckInServiceImpl;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.BufferedReader;
import java.math.BigDecimal;

/**
 * 入住控制器
 */
@RequestMapping("/api/checkin")
public class CheckInController {
    private ICheckInService checkInService = new CheckInServiceImpl();

    /**
     * 获取入住列表
     */
    @RequestMapping("/list")
    public void getCheckInList(HttpServletRequest request, HttpServletResponse response) {
        try {
            String pageNumStr = request.getParameter("pageNum");
            String pageSizeStr = request.getParameter("pageSize");
            
            int pageNum = pageNumStr != null ? Integer.parseInt(pageNumStr) : 1;
            int pageSize = pageSizeStr != null ? Integer.parseInt(pageSizeStr) : 10;
            
            PageInfo<CheckInVO> pageInfo = checkInService.getCheckInList(pageNum, pageSize);
            JSONUtil.printByJSON(response, Result.success(pageInfo));
        } catch (Exception e) {
            e.printStackTrace();
            JSONUtil.printByJSON(response, Result.error("获取入住列表失败"));
        }
    }

    /**
     * 获取在住客人
     */
    @RequestMapping("/currentGuests")
    public void getCurrentGuests(HttpServletRequest request, HttpServletResponse response) {
        try {
            String pageNumStr = request.getParameter("pageNum");
            String pageSizeStr = request.getParameter("pageSize");
            
            int pageNum = pageNumStr != null ? Integer.parseInt(pageNumStr) : 1;
            int pageSize = pageSizeStr != null ? Integer.parseInt(pageSizeStr) : 10;
            
            PageInfo<CheckInVO> pageInfo = checkInService.getCurrentGuests(pageNum, pageSize);
            JSONUtil.printByJSON(response, Result.success(pageInfo));
        } catch (Exception e) {
            e.printStackTrace();
            JSONUtil.printByJSON(response, Result.error("获取在住客人失败"));
        }
    }

    /**
     * 基于预订办理入住
     */
    @RequestMapping("/checkInWithReservation/*")
    public void checkInWithReservation(HttpServletRequest request, HttpServletResponse response) {
        try {
            String uri = request.getRequestURI();
            String idStr = uri.substring(uri.lastIndexOf("/") + 1);
            if (idStr.endsWith(".do")) {
                idStr = idStr.substring(0, idStr.length() - 3);
            }
            
            Integer reservationId = Integer.parseInt(idStr);
            
            // 获取操作员ID
            HttpSession session = request.getSession();
            UserVO user = (UserVO) session.getAttribute("user");
            if (user == null) {
                JSONUtil.printByJSON(response, Result.error(401, "请先登录"));
                return;
            }
            
            boolean success = checkInService.checkInWithReservation(reservationId, user.getId());
            
            if (success) {
                JSONUtil.printByJSON(response, Result.success("办理入住成功"));
            } else {
                JSONUtil.printByJSON(response, Result.fail("办理入住失败"));
            }
        } catch (Exception e) {
            e.printStackTrace();
            JSONUtil.printByJSON(response, Result.error("办理入住失败"));
        }
    }

    /**
     * Walk-in入住
     */
    @RequestMapping("/checkInWithoutReservation")
    public void checkInWithoutReservation(HttpServletRequest request, HttpServletResponse response) {
        try {
            BufferedReader reader = request.getReader();
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
            
            CheckInDTO dto = JSONUtil.fromJSON(sb.toString(), CheckInDTO.class);
            
            // 获取操作员ID
            HttpSession session = request.getSession();
            UserVO user = (UserVO) session.getAttribute("user");
            if (user == null) {
                JSONUtil.printByJSON(response, Result.error(401, "请先登录"));
                return;
            }
            
            boolean success = checkInService.checkInWithoutReservation(dto, user.getId());
            
            if (success) {
                JSONUtil.printByJSON(response, Result.success("办理入住成功"));
            } else {
                JSONUtil.printByJSON(response, Result.fail("办理入住失败"));
            }
        } catch (Exception e) {
            e.printStackTrace();
            JSONUtil.printByJSON(response, Result.error("办理入住失败"));
        }
    }

    /**
     * 办理退房
     */
    @RequestMapping("/checkOut")
    public void checkOut(HttpServletRequest request, HttpServletResponse response) {
        try {
            BufferedReader reader = request.getReader();
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
            
            // 解析请求参数
            String json = sb.toString();
            Integer id = JSONUtil.fromJSON(json, Integer.class);
            String totalAmountStr = request.getParameter("totalAmount");
            BigDecimal totalAmount = new BigDecimal(totalAmountStr != null ? totalAmountStr : "0");
            
            boolean success = checkInService.checkOut(id, totalAmount);
            
            if (success) {
                JSONUtil.printByJSON(response, Result.success("退房成功"));
            } else {
                JSONUtil.printByJSON(response, Result.fail("退房失败"));
            }
        } catch (Exception e) {
            e.printStackTrace();
            JSONUtil.printByJSON(response, Result.error("退房失败"));
        }
    }

    /**
     * 更新入住信息
     */
    @RequestMapping("/update")
    public void updateCheckIn(HttpServletRequest request, HttpServletResponse response) {
        try {
            BufferedReader reader = request.getReader();
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
            
            CheckInDTO dto = JSONUtil.fromJSON(sb.toString(), CheckInDTO.class);
            boolean success = checkInService.updateCheckIn(dto);
            
            if (success) {
                JSONUtil.printByJSON(response, Result.success("更新成功"));
            } else {
                JSONUtil.printByJSON(response, Result.fail("更新失败"));
            }
        } catch (Exception e) {
            e.printStackTrace();
            JSONUtil.printByJSON(response, Result.error("更新失败"));
        }
    }
}